var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);

var bgReady = false;
var bgImage = new Image();
bgImage.onload = function() {
	bgReady = true;
};
bgImage.src = "images/background.png";

var heroReady = false;
var heroImage = new Image();
heroImage.onload = function() {
	heroReady = true;
};
heroImage.src = "images/hero.png";

var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function() {
	monsterReady = true;
};
monsterImage.src = "images/monster.png";

var monster = {
	speed: 256
};
var hero = {};
var herosCaught = 0;

var keysDown = {};

addEventListener("keydown", function(e) {
	keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function(e) {
	delete keysDown[e.keyCode];
}, false);

var reset = function() {
	monster.x = canvas.width / 2;
	monster.y = canvas.height / 2;

	hero.x = 32 + (Math.random() * (canvas.width - 64));
	hero.y = 32 + (Math.random() * (canvas.height - 64));
};

var update = function(modifier) {
	if(38 in keysDown) {
		monster.y -= monster.speed * modifier;
	}
	if(40 in keysDown) {
		monster.y += monster.speed * modifier;
	}
	if(37 in keysDown) {
		monster.x -= monster.speed * modifier;
	}
	if(39 in keysDown) {
		monster.x += monster.speed * modifier;
	}

	if(
		monster.x <= (hero.x + 32) &&
		hero.x <= (monster.x + 32) &&
		monster.y <= (hero.y + 32) &&
		hero.y <= (monster.y + 32)
	) {
		++herosCaught;
		reset();
	}
};

var render = function() {
	if(bgReady) {
		ctx.drawImage(bgImage, 0, 0);
	}

	if(heroReady) {
		ctx.drawImage(heroImage, hero.x, hero.y);
	}

	if(monsterReady) {
		ctx.drawImage(monsterImage, monster.x, monster.y);
	}

	ctx.fillStyle = "rgb(250, 250, 250)";
	ctx.font = "24px Helvetica";
	ctx.textAlign = "left";
	ctx.textBaseline = "top";
	ctx.fillText("抓住的英雄：" + herosCaught, 32, 32);
};

var over = false;
var gameOver = function() {
	if(
		monster.x <= 0 ||
		monster.x >= canvas.width ||
		monster.y <= 0 ||
		monster.y >= canvas.height
	) {
		over = true;
		herosCaught = 0;
		reset();
	}
};

var main = function() {
	var now = Date.now();
	var delta = now - then;

	update(delta / 1000);
	gameOver();
	render();

	then = now;

	if(over == false){  
	       requestAnimationFrame(main);        
	    }  
	    
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

var then = Date.now();
reset();
main();